<template>
  <view class="publish-page">

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 标题输入 -->
      <view class="form-item">
        <input 
          class="title-input" 
          placeholder="请输入标题" 
          v-model="formData.title"
          maxlength="50"
        />
      </view>

      <!-- 分类选择 -->
      <view class="form-item">
        <view class="category-selector" @click="showCategoryPicker">
          <text class="category-text" :class="{ placeholder: !formData.category }">
            {{ formData.category || '未选择分类' }}
          </text>
          <text class="arrow-icon">›</text>
        </view>
      </view>

      <!-- 文件描述输入 -->
      <view class="form-item">
        <textarea 
          class="content-textarea" 
          placeholder="请输入文件描述" 
          v-model="formData.content"
          maxlength="2000"
          :auto-height="true"
        />
      </view>

      <!-- 文件上传 -->
      <view class="form-item">
        <view class="upload-section">
          <view class="upload-box file-upload" @click="uploadFile">
            <view class="upload-icon">
              <text class="upload-text">☁</text>
            </view>
            <view class="upload-content">
              <text class="upload-title">可上传文件</text>
              <view class="upload-btn">上传文件</view>
            </view>
          </view>
          <view class="upload-tips">
            支持上传.pdf, .doc, .docx, .ppt, .pptx, .xls, .xlsx的文件（必填）
          </view>
          
          <!-- 已上传的文件列表 -->
          <view class="uploaded-files" v-if="uploadedFiles.length > 0">
            <view 
              class="file-item" 
              v-for="(file, index) in uploadedFiles" 
              :key="index"
            >
              <view class="file-info">
                <text class="file-name">{{ file.name }}</text>
                <text class="file-size">{{ file.size }}</text>
              </view>
              <view class="file-delete" @click="removeFile(index)">×</view>
            </view>
          </view>
        </view>
      </view>

    </view>

    <!-- 底部发布按钮 -->
    <view class="bottom-actions">
      <view class="publish-btn" @click="confirmPublish" :class="{ disabled: !canPublish }">
        确认发布
      </view>
    </view>

    <!-- 分类选择器弹窗 -->
    <view class="category-picker" v-if="showPicker" @click="hideCategoryPicker">
      <view class="picker-content" @click.stop>
        <view class="picker-header">
          <text class="picker-title">选择分类</text>
          <text class="picker-close" @click="hideCategoryPicker">×</text>
        </view>
        <view class="picker-list">
          <view 
            class="picker-item" 
            v-for="item in categoryOptions" 
            :key="item.id"
            @click="selectCategory(item)"
          >
            {{ item.typeName || item.name }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getTechWikiFileTypeList, createTechWikiFile } from '@/api/api.js'

export default {
  name: 'PublishDetail',
  data() {
    return {
      formData: {
        title: '',
        category: '',
        content: '',
        fileTypeId: null
      },
      uploadedFiles: [],
      showPicker: false,
      categoryOptions: [],
      selectedFile: null
    }
  },
  computed: {
    canPublish() {
      return this.formData.title.trim() && 
             this.formData.category && 
             this.formData.content.trim() && 
             this.selectedFile
    }
  },
  onLoad() {
    // 页面加载时加载分类列表
    this.loadCategories()
  },
  methods: {
    // 加载分类列表
    async loadCategories() {
      try {
        const response = await getTechWikiFileTypeList()
        if (response.code === 200) {
          // 使用接口返回的数据，显示fileTypeName字段
          this.categoryOptions = response.data || []
        } else {
          uni.showToast({
            title: response.message || '加载文件类型失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载文件类型失败:', error)
        uni.showToast({
          title: '加载文件类型失败',
          icon: 'none'
        })
      }
    },

    // 显示分类选择器
    showCategoryPicker() {
      this.showPicker = true
    },

    // 隐藏分类选择器
    hideCategoryPicker() {
      this.showPicker = false
    },

    // 选择分类
    selectCategory(category) {
      // 使用接口返回的typeName字段显示分类名称
      this.formData.category = category.typeName || category.name
      this.formData.fileTypeId = category.id
      this.showPicker = false
    },

    // 上传文件
    uploadFile() {
      uni.showActionSheet({
        itemList: ['选择文件', '拍照'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.chooseFile()
          } else {
            this.takePhoto()
          }
        }
      })
    },

    // 选择文件
    chooseFile() {
      // 小程序中使用uni.chooseMessageFile选择文件
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'],
        success: (res) => {
          const file = res.tempFiles[0]
          this.selectedFile = file
          this.uploadedFiles = [{
            name: file.name,
            size: this.formatFileSize(file.size),
            url: file.path
          }]
          
          uni.showToast({
            title: '文件选择成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('选择文件失败:', err)
          uni.showToast({
            title: '选择文件失败，请重试',
            icon: 'none'
          })
        }
      })
    },

    // 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          const file = {
            path: tempFilePaths[0],
            name: '拍照文件.jpg',
            size: 0 // 拍照文件大小无法直接获取
          }
          this.selectedFile = file
          this.uploadedFiles = [{
            name: file.name,
            size: '未知大小',
            url: file.path
          }]
          
          uni.showToast({
            title: '文件选择成功',
            icon: 'success'
          })
        }
      })
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 删除文件
    removeFile(index) {
      this.uploadedFiles.splice(index, 1)
      this.selectedFile = null
    },

    // 确认发布
    async confirmPublish() {
      if (!this.canPublish) {
        uni.showToast({
          title: '请完善必填信息',
          icon: 'none'
        })
        return
      }

      // 检查登录状态 - 使用store中的token
      if (!this.$store.state.app.token) {
        uni.showModal({
          title: '提示',
          content: '请先登录后再发布文档',
          showCancel: true,
          cancelText: '取消',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/users/login/index'
              })
            }
          }
        })
        return
      }

      uni.showLoading({
        title: '发布中...'
      })

      try {
        // 检查文件是否存在
        if (!this.selectedFile) {
          throw new Error('没有选择文件')
        }
        
        // 使用uni.uploadFile上传文件
        const uploadResult = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: 'http://192.168.2.119:8081/api/front/techwiki/file/create',
            filePath: this.selectedFile.path,
            name: 'file',
            formData: {
              fileName: this.formData.title,
              fileDesc: this.formData.content,
              fileTypeId: this.formData.fileTypeId
            },
            header: {
              'Authori-zation': this.$store.state.app.token
            },
            success: (res) => {
              try {
                const data = JSON.parse(res.data)
                resolve(data)
              } catch (e) {
                reject(new Error('响应解析失败'))
              }
            },
            fail: (err) => {
              console.error('上传失败:', err)
              reject(err)
            }
          })
        })
        
        if (uploadResult.code === 200) {
          uni.hideLoading()
          uni.showToast({
            title: '发布成功',
            icon: 'success'
          })
          
          // 发布成功后返回列表页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else if (uploadResult.code === 401) {
          // 处理401未授权错误
          uni.hideLoading()
          uni.showModal({
            title: '登录过期',
            content: '您的登录已过期，请重新登录',
            showCancel: false,
            confirmText: '去登录',
            success: () => {
              uni.navigateTo({
                url: '/pages/users/login/index'
              })
            }
          })
        } else {
          uni.hideLoading()
          uni.showToast({
            title: uploadResult.message || '发布失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('发布失败:', error)
        uni.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.publish-page {
  background-color: #F5F5F5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}


/* 表单内容 */
.form-content {
  padding: 32rpx;
}

.form-item {
  margin-bottom: 32rpx;
}

/* 标题输入 */
.title-input {
  width: 100%;
  height: 88rpx;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333333;
  border: 1rpx solid #E0E0E0;
}

.title-input::placeholder {
  color: #999999;
}

/* 分类选择 */
.category-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 0 24rpx;
  border: 1rpx solid #E0E0E0;
}

.category-text {
  font-size: 28rpx;
  color: #333333;
}

.category-text.placeholder {
  color: #999999;
}

.arrow-icon {
  font-size: 32rpx;
  color: #999999;
}

/* 内容输入 */
.content-textarea {
  width: 100%;
  min-height: 300rpx;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 24rpx;
  font-size: 28rpx;
  color: #333333;
  border: 1rpx solid #E0E0E0;
  line-height: 1.6;
}

.content-textarea::placeholder {
  color: #999999;
}

/* 上传区域 */
.upload-section {
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 24rpx;
  border: 1rpx solid #E0E0E0;
}

.upload-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 160rpx;
  border: 2rpx dashed #D0D0D0;
  border-radius: 8rpx;
  background-color: #FAFAFA;
}

.upload-icon {
  margin-right: 24rpx;
}

.upload-text {
  font-size: 48rpx;
  color: #2196F3;
}

.upload-content {
  text-align: center;
}

.upload-title {
  display: block;
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 16rpx;
}

.upload-btn {
  background-color: #2196F3;
  color: #FFFFFF;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: 1rpx solid #1976D2;
}

.upload-tips {
  font-size: 22rpx;
  color: #999999;
  margin-top: 16rpx;
  line-height: 1.4;
}

/* 已上传文件 */
.uploaded-files {
  margin-top: 24rpx;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  margin-bottom: 12rpx;
}

.file-info {
  flex: 1;
}

.file-name {
  display: block;
  font-size: 26rpx;
  color: #333333;
  margin-bottom: 4rpx;
}

.file-size {
  font-size: 22rpx;
  color: #999999;
}

.file-delete {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #FF4444;
  color: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
}


/* 底部发布按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  padding: 20rpx 32rpx;
  border-top: 1rpx solid #F0F0F0;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.publish-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  background: linear-gradient(135deg, #FF4444 0%, #FF8800 100%);
  color: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  transition: all 0.3s ease;
}

.publish-btn.disabled {
  background: #CCCCCC;
  color: #999999;
}

.publish-btn:active:not(.disabled) {
  opacity: 0.8;
  transform: scale(0.98);
}

/* 分类选择器弹窗 */
.category-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.picker-content {
  width: 100%;
  background-color: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.picker-close {
  font-size: 40rpx;
  color: #999999;
  font-weight: bold;
}

.picker-list {
  max-height: 60vh;
  overflow-y: auto;
}

.picker-item {
  padding: 32rpx;
  border-bottom: 1rpx solid #F0F0F0;
  font-size: 28rpx;
  color: #333333;
}

.picker-item:last-child {
  border-bottom: none;
}
</style>